package com.banciyuan.bcywebview.biz.share;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.detail.adapter.DetailConstants;
import com.banciyuan.bcywebview.biz.detail.tags.EditDetailTagsActivity;
import com.banciyuan.bcywebview.biz.post.cos.CosEditActivity;
import com.banciyuan.bcywebview.biz.post.illust.illustEditActivity;
import com.banciyuan.bcywebview.biz.post.write.EditArticleActivity;
import com.banciyuan.bcywebview.biz.post.write.series.SeriesEditActivity;
import com.banciyuan.bcywebview.biz.privatemessage.EditPrivateMessageActivity;
import com.banciyuan.bcywebview.biz.report.ReportActivity;
import com.banciyuan.bcywebview.biz.report.UserReportActivity;
import com.banciyuan.bcywebview.biz.share.block.BlockHelper;
import com.banciyuan.bcywebview.biz.share.block.IBlockHelper;
import com.banciyuan.bcywebview.biz.write.DailyEditActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sns.SnsUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.PrivateMessage;
import de.greenrobot.daoexample.model.Timeline;
import de.greenrobot.daoexample.model.UserDetail;

/**
 * Created by squall on 2015/8/19.
 */
public class ShareActivity extends BaseActivity implements View.OnClickListener, WbShareCallback {

    private ImageView qq;
    private ImageView wechat;
    private ImageView friend;
    private ImageView weibo;
    private ImageView qqzone;
    private ImageView delete;
    private ImageView report;
    private ImageView edit;
    private ImageView edit_tag;
    private ImageView block;
    private ImageView copy;
    private ImageView privateMessage;
    private TextView block_tv;

    private LinearLayout share_line;
    private LinearLayout control_line;

    private TextView cancel;
    private Timeline timeline;
    private LinearLayout cancel_line;
    private ImageLoader imageLoading;
    private RequestQueue queue;

    private boolean showDelBtn;
    private boolean showWarnBtn;
    private boolean showblock;
    private boolean showCopyLink;
    private boolean showShare;
    private boolean showEdit;
    private boolean showPrivate;
    private boolean is_zhipin;
    private boolean is_group;
    private boolean orientation;

    private View line_split;
    private Map<String, String> map = new HashMap<>();
    private WbShareHandler shareHandler;
    private IWXAPI mWxApi;
    private Tencent mTencent;

    private UserDetail user;
    private IBlockHelper iBlockHelper;

    public static final int EDIT_TAGS = 1000;
    public static final int DELETE = 2001;
    public static final int BLOCK = 2002;

    private JumpDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_more_layout);
        initArgs();
        ImplIBlockHelper();
        initUi();
        initAction();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        shareHandler.doResultIntent(intent, this);
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
        timeline = (Timeline) getIntent().getSerializableExtra("timeline");
        map = (Map<String, String>) getIntent().getSerializableExtra("map");
        showDelBtn = getIntent().getBooleanExtra("showDelBtn", false);
        showWarnBtn = getIntent().getBooleanExtra("showWarnBtn", true);
        showblock = getIntent().getBooleanExtra("showblock", false);
        showCopyLink = getIntent().getBooleanExtra("showCopyLink", true);
        showShare = getIntent().getBooleanExtra("showShare", true);
        showEdit = getIntent().getBooleanExtra("showEdit", false);
        showPrivate = getIntent().getBooleanExtra("showPrivate", false);
        is_zhipin = getIntent().getBooleanExtra("is_zhipin", false);
        is_group = getIntent().getBooleanExtra("is_group", false);
        orientation = getIntent().getBooleanExtra("orientation", false);
        if (orientation) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        user = (UserDetail) getIntent().getSerializableExtra("user");
        imageLoading = ImageLoader.getInstance();
        //初始化qq分享
        mTencent = Tencent.createInstance(MyConstants.QQ_LOGIN_APP_ID, getContext());
        //初始化微博分享

        shareHandler = new WbShareHandler(this);
        shareHandler.registerApp();
        //初始化微信分享
        mWxApi = WXAPIFactory.createWXAPI(this, MyConstants.WEIXIN_APP_ID, true);
        mWxApi.registerApp(MyConstants.WEIXIN_APP_ID);
        if (timeline != null) {
            map = SnsUtil.parseTimeLine(timeline, ShareActivity.this);
        }
    }


    @Override
    protected void initAction() {
        qq.setOnClickListener(this);
        wechat.setOnClickListener(this);
        friend.setOnClickListener(this);
        weibo.setOnClickListener(this);
        qqzone.setOnClickListener(this);
        delete.setOnClickListener(this);
        report.setOnClickListener(this);
        cancel.setOnClickListener(this);
        edit.setOnClickListener(this);
        edit_tag.setOnClickListener(this);
        copy.setOnClickListener(this);
        cancel_line.setOnClickListener(this);
        block.setOnClickListener(this);
        privateMessage.setOnClickListener(this);
    }

    @Override
    protected void initUi() {
        qq = (ImageView) findViewById(R.id.iv_qq);
        wechat = (ImageView) findViewById(R.id.iv_wechat);
        friend = (ImageView) findViewById(R.id.iv_friend);
        weibo = (ImageView) findViewById(R.id.iv_weibo);
        qqzone = (ImageView) findViewById(R.id.iv_qqzone);
        delete = (ImageView) findViewById(R.id.iv_delete);
        report = (ImageView) findViewById(R.id.iv_report);
        cancel = (TextView) findViewById(R.id.tv_cancle);
        edit = (ImageView) findViewById(R.id.iv_edit);
        edit_tag = (ImageView) findViewById(R.id.iv_edit_tag);
        block = (ImageView) findViewById(R.id.iv_block);
        copy = (ImageView) findViewById(R.id.iv_copy_link);
        line_split = findViewById(R.id.line_split);
        share_line = (LinearLayout) findViewById(R.id.share_line);
        control_line = (LinearLayout) findViewById(R.id.control_line);
        cancel_line = (LinearLayout) findViewById(R.id.cancel_line);
        block_tv = (TextView) findViewById(R.id.tv_block);
        privateMessage = (ImageView) findViewById(R.id.iv_private_link);
        if (user != null) {
            if (user.getIs_blocked() == 1) {
                block_tv.setText(getString(R.string.deletefrom_blocklist));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    block.setImageDrawable(getResources().getDrawable(R.drawable.block_out, getTheme()));
                } else {
                    block.setImageDrawable(getResources().getDrawable(R.drawable.block_out));
                }
            } else {
                block_tv.setText(getString(R.string.putinto_blocklist));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    block.setImageDrawable(getResources().getDrawable(R.drawable.block_in, getTheme()));
                } else {
                    block.setImageDrawable(getResources().getDrawable(R.drawable.block_in));
                }
            }
        }
        int gonenum = 0;

        if (showCopyLink) {
            ((View) (copy.getParent())).setVisibility(View.VISIBLE);
        } else {
            ((View) (copy.getParent())).setVisibility(View.GONE);
            gonenum++;
        }
        if (showblock) {
            ((View) (block.getParent())).setVisibility(View.VISIBLE);
        } else {
            ((View) (block.getParent())).setVisibility(View.GONE);
            gonenum++;
        }
        if (showWarnBtn) {
            if (user != null) {
                ((View) (report.getParent())).setVisibility(View.VISIBLE);
            } else if (timeline != null && !timeline.getUid().equals(UserDataHelper.getInstance(ShareActivity.this).getUid())) {
                ((View) (report.getParent())).setVisibility(View.VISIBLE);
            } else if (is_group) {
                ((View) (report.getParent())).setVisibility(View.VISIBLE);
            } else {
                ((View) (report.getParent())).setVisibility(View.GONE);
                gonenum++;
            }
        } else {
            ((View) (report.getParent())).setVisibility(View.GONE);
            gonenum++;
        }

        if ((timeline != null && can_edit())) {
            if (timeline.getUid().equals(UserDataHelper.getInstance(ShareActivity.this).getUid())) {
                ((View) (edit.getParent())).setVisibility(View.VISIBLE);
            } else {
                ((View) (edit.getParent())).setVisibility(View.GONE);
                gonenum++;
            }
        } else {
            if (!showEdit) {
                ((View) (edit.getParent())).setVisibility(View.GONE);
                gonenum++;
            } else {
                ((View) (edit.getParent())).setVisibility(View.VISIBLE);
            }
        }

        if (timeline != null && can_edit_tag()) {
            if (timeline.getUid().equals(UserDataHelper.getInstance(ShareActivity.this).getUid())) {
                ((View) (edit_tag.getParent())).setVisibility(View.VISIBLE);
            } else {
                ((View) (edit_tag.getParent())).setVisibility(View.GONE);
                gonenum++;
            }
        } else {
            ((View) (edit_tag.getParent())).setVisibility(View.GONE);
            gonenum++;
        }

        if (timeline != null) {
            if (showDelBtn) {
                ((View) (delete.getParent())).setVisibility(View.VISIBLE);
            } else {
                ((View) (delete.getParent())).setVisibility(View.GONE);
                gonenum++;
            }
        } else {
            if (!showDelBtn) {
                ((View) (delete.getParent())).setVisibility(View.GONE);
                gonenum++;
            } else {
                ((View) (delete.getParent())).setVisibility(View.VISIBLE);
            }
        }
        if (!showPrivate) {
            ((View) (privateMessage.getParent())).setVisibility(View.GONE);
            gonenum++;
        } else {
            ((View) (privateMessage.getParent())).setVisibility(View.VISIBLE);
        }

        if (gonenum >= 7) {
            line_split.setVisibility(View.GONE);
        } else {
            line_split.setVisibility(View.VISIBLE);
        }
        if (showShare) {
            share_line.setVisibility(View.VISIBLE);
            control_line.setPadding(0, UIUtils.dip2px(16, ShareActivity.this), 0, 0);
        } else {
            share_line.setVisibility(View.GONE);
            line_split.setVisibility(View.GONE);
            control_line.setPadding(0, 0, 0, 0);
        }


    }

    private boolean can_edit() {
        switch (timeline.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                return true;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                return true;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                return true;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                return !StringUtil.notNullEqual(timeline.getType(), "larticle") && !StringUtil.notNullEqual(timeline.getType(), "svideo");
            default:
                return false;
        }
    }

    private boolean can_edit_tag() {
        switch (timeline.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                return true;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                return true;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                return true;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                return true;
            default:
                return false;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_qq:
                SnsUtil.share2QQ(this, map, mTencent);
                break;
            case R.id.iv_wechat:
                if (mWxApi.isWXAppInstalled()) {
                    SnsUtil.share2Weixin(this, map, mWxApi);
                } else {
                    MyToast.show(this, getString(R.string.weixin_notinstalled));
                }
                break;
            case R.id.iv_friend:
                if (mWxApi.isWXAppInstalled()) {
                    SnsUtil.share2Circle(this, map, mWxApi);
                } else {
                    MyToast.show(this, getString(R.string.weixin_notinstalled));
                }
                break;
            case R.id.iv_weibo:
                showWeiboJumpDialog();
                SnsUtil.share2Weibo(shareHandler, map);
                break;
            case R.id.iv_qqzone:
                SnsUtil.shareToQQZone(this, map, mTencent);
                break;
            case R.id.iv_delete:
                alertDel();
                break;
            case R.id.iv_report:
                gotoReport();
                break;
            case R.id.tv_cancle:
                close();
                break;
            case R.id.cancel_line:
                close();
                break;
            case R.id.iv_edit:
                goEdit();
                break;
            case R.id.iv_edit_tag:
                goEditTag();
                break;
            case R.id.iv_block:
                block();
                break;
            case R.id.iv_copy_link:
                copy_link();
                break;
            case R.id.iv_private_link:
                gotoMessage();
                break;

        }
    }

    private void gotoMessage() {
        PrivateMessage privateMessage = new PrivateMessage();
        privateMessage.setUid(user.getUid());
        privateMessage.setUname(user.getUname());
        gotoUtil.gotoAct(this, EditPrivateMessageActivity.class, privateMessage, "new");
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private void copy_link() {
        ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("shareUrl", map.get("url"));
        clip.setPrimaryClip(clipData);
        MyToast.show(this, getString(R.string.copy_complate));
        close();
    }

    private void goEditTag() {
        Intent intent = new Intent();
        intent.putExtra("tags", (Serializable) timeline.getTags());
        intent.putExtra("type", timeline.getTimelineType());
        intent.putExtra("id", timeline.getRp_id());
        intent.putExtra("ud_id", timeline.getUd_id());
        intent.putExtra("work", timeline.getWork());
        intent.putExtra("worktype", timeline.getType());
        intent.putStringArrayListExtra("character", timeline.getOriginalRoleNames());
        intent.setClass(this, EditDetailTagsActivity.class);
        startActivityForResult(intent, EDIT_TAGS);
    }

    private void goEdit() {
        Intent intent = new Intent();
        DetailType detailType = new DetailType();
        if (timeline != null && can_edit()) {
            switch (timeline.getTimelineType()) {
                case TimelineFactory.TIMELINE_TYPE_COSER:
                    detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_COSER);
                    detailType.setCp_id(timeline.getCp_id());
                    detailType.setRp_id(timeline.getRp_id());
                    intent.putExtra("edit_data", detailType);
                    intent.setClass(ShareActivity.this, CosEditActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case TimelineFactory.TIMELINE_TYPE_ILLUST:
                    detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_ILLUST);
                    detailType.setDp_id(timeline.getDp_id());
                    detailType.setRp_id(timeline.getRp_id());
                    intent.putExtra("edit_data", detailType);
                    intent.setClass(ShareActivity.this, illustEditActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case TimelineFactory.TIMELINE_TYPE_WRITER:
                    detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_WRITER);
                    detailType.setWp_id(timeline.getWp_id());
                    detailType.setRp_id(timeline.getRp_id());
                    intent.putExtra("edit_data", detailType);
                    intent.setClass(ShareActivity.this, EditArticleActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case TimelineFactory.TIMELINE_TYPE_DAILY:
                    detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_DAILY);
                    detailType.setUd_id(timeline.getUd_id());
                    intent.putExtra("edit_data", detailType);
                    intent.setClass(ShareActivity.this, DailyEditActivity.class);
                    startActivity(intent);
                    finish();
                    break;
            }
        } else {
            intent.putExtra(HttpUtils.WNS_ID, map.get(HttpUtils.WNS_ID));
            intent.setClass(ShareActivity.this, SeriesEditActivity.class);
            startActivity(intent);
            finish();
        }
    }

    private void ImplIBlockHelper() {
        iBlockHelper = new IBlockHelper() {
            @Override
            public void getSucc(String json) {
                try {
                    Intent intent = new Intent();
                    JSONObject jsonObject = new JSONObject(json);
                    MyToast.show(ShareActivity.this, jsonObject.getString(HttpUtils.UPLOAD_DATA));
                    if (user.getIs_blocked() == 0) {
                        user.setIs_blocked(1);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            block.setImageDrawable(getResources().getDrawable(R.drawable.block_out, getTheme()));
                        } else {
                            block.setImageDrawable(getResources().getDrawable(R.drawable.block_out));
                        }
                        block_tv.setText(getString(R.string.deletefrom_blocklist));
                        intent.putExtra("is_block", 1);
                        setResult(ShareActivity.BLOCK, intent);
                    } else {
                        user.setIs_blocked(0);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            block.setImageDrawable(getResources().getDrawable(R.drawable.block_in, getTheme()));
                        } else {
                            block.setImageDrawable(getResources().getDrawable(R.drawable.block_in));
                        }
                        block_tv.setText(getString(R.string.putinto_blocklist));
                        intent.putExtra("is_block", 0);
                        setResult(ShareActivity.BLOCK, intent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void getFail() {
                MyToast.show(ShareActivity.this, getString(R.string.operation_fail));
            }
        };
    }

    private void block() {
        if (user == null) return;
        final BlockHelper blockHelper = new BlockHelper(iBlockHelper, ShareActivity.this);
        if (user.getIs_blocked() == 0) {
            View.OnClickListener comfirmAction = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    blockHelper.doBlock(UserDataHelper.getInstance(ShareActivity.this).getToken(), user.getUid());
                }
            };
            ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
            builder.setDescString(getString(R.string.enter_block_list))
                    .setActionString(getString(R.string.comfirm_to_block_list))
                    .setCancelString(getString(R.string.mydialog_cancel))
                    .setActionClickListener(comfirmAction).create().show();
        } else {
            blockHelper.unBlock(UserDataHelper.getInstance(this).getToken(), user.getUid());
        }
        setResult(ShareActivity.BLOCK);
    }

    private void gotoReport() {
        if (timeline != null) {
            Intent intent = new Intent(this, ReportActivity.class);
            DetailDataHelper.putBaseDetailValue(intent, timeline);
            startActivity(intent);
        } else if (user != null) {
            Intent intent = new Intent(this, UserReportActivity.class);
            intent.putExtra("user", user);
            startActivity(intent);
        } else if (is_group) {
            Intent intent = new Intent(this, ReportActivity.class);
            intent.putExtra(gotoUtil.INTENT_VALUE_ONE, 2);
            intent.putExtra(gotoUtil.INTENT_VALUE_THREE, map.get("gid"));
            startActivity(intent);
        } else {
            MyToast.show(this, getString(R.string.report_up_succ));
        }
    }

    private void alertDel() {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.confrim_to_delete))
                .setActionString(getString(R.string.mydialog_delete))
                .setCancelString(getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delPost();
                    }
                })
                .create().show();
    }

    public void delPost() {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, ShareActivity.this)) {
                    setResult(DELETE);
                    close();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        };
        if (timeline != null) {
            CommonApiUtils.delPost(ShareActivity.this, queue, onSuccess, onError, timeline);
        } else {
            CommonApiUtils.delSerise(ShareActivity.this, queue, onSuccess, onError, map.get("wns_id"));
        }
    }

    private void close() {
        finish();
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            close();
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == EDIT_TAGS) {
            setResult(DetailConstants.EDIT_TAGS, data);
            close();
        }
    }

    private void showWeiboJumpDialog() {
        JumpDialog.Builder builder = new JumpDialog.Builder(this);
        dialog = builder.create();
        dialog.show();
    }

    private void dismissDialog() {
        if (dialog != null && !isFinishing() && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onWbShareSuccess() {
        dismissDialog();
        MyToast.show(this, getString(R.string.weibosdk_demo_toast_share_success));
    }

    @Override
    public void onWbShareCancel() {
        dismissDialog();
        MyToast.show(this, getString(R.string.weibosdk_demo_toast_share_cancel));

    }

    @Override
    public void onWbShareFail() {
        dismissDialog();
        MyToast.show(this, getString(R.string.weibosdk_demo_toast_share_success));
    }
}